# encoding=utf8

from flask import current_app, flash
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import SignatureExpired, BadSignature
from app.extensions import db, login_manager


class User(UserMixin, db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(32), nullable=False, unique=True)
    password_hash = db.Column(db.String(128), nullable=False)
    email = db.Column(db.String(64), nullable=False, unique=True)
    confirm = db.Column(db.Boolean, default=False)
    icon = db.Column(db.String(64), default='default.jpg')

    def __repr__(self):
        return self.username

    def avatars(self):
        return '/static/uploads/' + self.icon

    @property
    def password(self):
        raise AttributeError('密码是不可读属性')

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def generate_activate_token(self):
        s = Serializer(current_app.config['SECRET_KEY'])
        return s.dumps({'id': self.id})

    @staticmethod
    def generate_token(dic):
        s = Serializer(current_app.config['SECRET_KEY'])
        return s.dumps(dic)

    @staticmethod
    def check_token(token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except SignatureExpired:
            flash('邮件已过期')
            return False
        except BadSignature:
            flash('无效的验证邮箱')
            return False
        return data

    @staticmethod
    def check_activate_token(token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
            print(data)
        except SignatureExpired:
            flash('激活邮件已过期')
            return False
        except BadSignature:
            flash('无效的激活')
            return False
        user = User.query.get(data.get('id'))
        print(user)
        if not user:
            flash('激活的账户不存在')
            return False
        if not user.confirm:
            user.confirm = True
            db.session.add(user)
        return True

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)

    @staticmethod
    def add(user):
        try:
            db.session.add(user)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            raise Exception('add user failed')


@login_manager.user_loader
def load_user(uid):
    return User.query.get(int(uid))
